package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;


    @Autowired
    private IElderService elderService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IContractService contractService;

    @Autowired
    private ICheckInConfigService checkInConfigService;
    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
       /* //检验老人是否已入住
        //select * from elder where idCardNo=?
        Elder elder =elderService.lambdaQuery()
                .eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo())
                        .one();
        if (elder!=null&&elder.getStatus()==1){
            throw new RuntimeException("该老头已入住");
        }
        //更新床位状态
        Bed bed = new Bed();
        bed.setBedStatus(1);
        bed.setId(dto.getCheckInConfigDto().getBedId());
        bedService.updateBed(bed);
        //根据Id查询床位
        Bed dbbed=bedService.getById(dto.getCheckInConfigDto().getBedId());
        if (dbbed==null){
            throw new RuntimeException("床木得了");
        }
        //新增或更新老人
        Elder newElder= BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        newElder.setStatus(1);
        newElder.setBedId(dto.getCheckInConfigDto().getBedId());
        newElder.setBedNumber(dbbed.getBedNumber());
        elderService.saveOrUpdate(newElder);
        //新增签约办理
        Contract contract=BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(newElder.getId());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderName(newElder.getName());
        LocalDateTime startDate= dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate=dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(LocalDateTime.now().isAfter(startDate)?1:0);
        contractService.save( contract);
        //新增入住信息
        CheckIn checkIn=BeanUtil.toBean(dto.getCheckInContractDto(), CheckIn.class);
        checkIn.setElderName(newElder.getName());
        checkIn.setElderId(newElder.getId());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setBedNumber(dbbed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        this.save(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig=BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);*/
        //检验老人是否已入住 sql select * from elder where idcardno=?
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .one();
        if(elder!=null&&elder.getStatus()==1){
            throw new RuntimeException("老登儿,你在玩火");
        }
        //更新床位状态为已入住 sql update bed set bed_status=1 where id=?
        bedService.lambdaUpdate()
                .set(Bed::getBedStatus,1)
                .eq(Bed::getId,dto.getCheckInConfigDto().getBedId())
                .update();
        //先查询床位编号
        Bed bed = bedService.selectBedById(dto.getCheckInConfigDto().getBedId());
        if(bed==null){
            throw new RuntimeException("木得床了");
        }
        //新增或更新老人
        Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        if(elder!=null&&elder.getId()!=null){
            newElder.setId(elder.getId());
        }
        newElder.setStatus(1);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());
        elderService.saveOrUpdate(newElder);//只要id为空就执行新增,id不为空
        //新增签约办理
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(newElder.getId());
        contract.setElderName(newElder.getName());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //如果现在时间在开始时间之后就是 已生效 否则未生效
        contract.setStatus(LocalDateTime.now().isAfter(startDate)?1:0);
        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderName(newElder.getName());
        checkIn.setElderId(newElder.getId());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        this.save(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckInElderVo vo = new CheckInElderVo();
        //查询入住信息
        CheckIn byId = this.getById(id);
        //查询老人信息 select * from elder left join check_in where check_in.elder_id=elder.id
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getId,byId.getElderId())
                .one();
        CheckInElderVo elderVo = BeanUtil.toBean(elder, CheckInElderVo.class);//查询合同 select * from contract where contract.elder_id=elder.id
        Contract contract=contractService.lambdaQuery()
                .eq(Contract::getElderId,elder.getId())
                .one();
        //查询入住配置 select * from check_in_config where check_in_config.check_in_id=check_in.id
        CheckInConfig checkInConfigEntity=checkInConfigService.lambdaQuery()
                .eq(CheckInConfig::getCheckInId,id)
                .one();
        /*CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtil.copyProperties(checkInConfigEntity,checkInConfigVo);*/
        CheckInConfigVo bean = BeanUtil.toBean(checkInConfigEntity, CheckInConfigVo.class);
        bean.setStartDate(byId.getStartDate());
        bean.setEndDate(byId.getEndDate());
        bean.setBedNumber(byId.getBedNumber());
        //转换家属列表 select * from elder_family where elder_family.elder_id=elder.id
        //把入住表中的remark字段转换成实体类
        List<ElderFamilyVo> list = JSONUtil.toList(byId.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(list);
        //整合数据返回
        // 设置各个部分的数据
        checkInDetailVo.setCheckInElderVo(elderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setCheckInConfigVo(bean);
        checkInDetailVo.setElderFamilyVoList(list);
        return checkInDetailVo;
    }
}
